import { DragView } from '@renderer/components/Utils'
import React, { useEffect, useState } from 'react'

export default function SoundRecordingPage(): React.JSX.Element {
  const [isRecording, setIsRecording] = useState<boolean>(false)
  // 录制器
  const [mediaRecorder, setMediaRecorder] = useState<MediaRecorder | undefined>()
  // 视频收集
  let recordedChunks: Blob[] = []
  const [time, setTime] = useState<string>('00')
  const [stream, setStream] = useState<MediaStream | undefined>()

  const [toastMessage, setToastMessage] = useState<{
    success: boolean
    message: string
  }>({
    success: false,
    message: ''
  })
  const startRecording = (): void => {
    setIsRecording(!isRecording)
    recording()
  }

  const stopRecording = (): void => {
    setIsRecording(!isRecording)
    mediaRecorder?.stop()
  }

  function recording(): void {
    // 录制音频
    const medias = navigator.mediaDevices.getUserMedia({
      audio: true,
      video: false
    })

    medias.then((stream) => {
      setStream(stream)
      setMediaRecorder(
        new MediaRecorder(stream, {
          mimeType: 'video/webm; codecs=vp9',
          videoBitsPerSecond: 2500000 // 2.5 Mbps
        })
      )
    })
  }

  const resetData = (): void => {
    setMediaRecorder(undefined)
    recordedChunks = []
    setTime('00')
    if (stream) {
      stream.getTracks().forEach((track) => track.stop())
    }
    setStream(undefined)
  }
  useEffect(() => {
    if (mediaRecorder) {
      const startTime = Date.now()
      mediaRecorder.ondataavailable = (e) => {
        if (e.data.size > 0) {
          const currentTime = Date.now()
          const elapsedSeconds = Math.round((currentTime - startTime) / 1000)
          // console.log(elapsedSeconds)
          const hrs = Math.floor(elapsedSeconds / 3600)
          const mins = Math.floor((elapsedSeconds % 3600) / 60)
          const secs = elapsedSeconds % 60
          setTime(
            [
              hrs.toString().padStart(2, '0'),
              mins.toString().padStart(2, '0'),
              secs.toString().padStart(2, '0')
            ]
              .filter((item) => item !== '00')
              .join(':')
          )
          recordedChunks.push(e.data)
        }
      }
      // 录制视频结束
      mediaRecorder.onstop = async () => {
        // 创建 Blob
        const blob = new Blob(recordedChunks, {
          type: 'video/webm'
        })
        resetData()
        // 转换为 ArrayBuffer
        const arrayBuffer = await blob.arrayBuffer()
        console.log('arrayBuffer', arrayBuffer)
        // 发送给主进程
        const res = await window.electron.ipcRenderer.invoke('save:recording:music', arrayBuffer)
        setToastMessage(res)
      }
      mediaRecorder.start(1000)
    }
  }, [mediaRecorder])

  const onClose = () => {
    resetData()
    window.electron.ipcRenderer.send('close:win')
  }
  return (
    <DragView>
      {!toastMessage.success ? (
        <div className="w-full h-full rounded-[50%] bg-gradient-to-r from-[#e84e40] to-[#ff7e5f] border-[#d45d28] flex justify-center items-center border-[1px]">
          {!isRecording ? (
            <div
              className="border-[#999] bg-[red] w-1/2 h-1/2 border-[1px] rounded-[50%] scale-70 flex justify-center items-center"
              onClick={startRecording}
            >
              start
            </div>
          ) : (
            // 取消录音
            <div className="bg-[black] w-6/7 h-6/7 rounded-[50%] flex justify-center items-center">
              <div
                className="bg-gradient-to-r from-[#e84e40] to-[#ff7e5f] border-[#999] border-2 w-1/2 h-1/2 flex flex-col justify-center items-center scale-100 rounded-[10px]"
                onClick={stopRecording}
              >
                <p className="text-[11.5px] text-[#eee]">{time}</p>
              </div>
            </div>
          )}
        </div>
      ) : (
        <div className="w-full h-full rounded-[10px] bg-gradient-to-r from-[#e84e40] to-[#ff7e5f] border-[#d45d28] flex justify-center items-center border-[1px]">
          <div className="bg-[#28b462] w-6/7 h-6/7 rounded-[10px] flex flex-col gap-[20px] justify-center items-center" onClick={onClose}>
            <p>关闭</p>
            <p>{toastMessage.message}</p>
          </div>
        </div>
      )}
    </DragView>
  )
}
